package com.houduan.controller;

import com.houduan.dao.OrderDao;
import com.houduan.dao.UserDao;
import com.houduan.model.Order;
import com.houduan.model.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class OrderServlet extends HttpServlet {

    private OrderDao orderDao;
    private UserDao userDao;

    @Override
    public void init() throws ServletException {
        super.init();
        orderDao = new OrderDao(); // 初始化 OrderDao
        userDao = new UserDao();   // 初始化 UserDao
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String action = request.getParameter("action");

        if (action == null) {
            action = "list"; // 默认执行列出订单操作
        }

        switch (action) {
            case "list":
                listOrders(request, response);
                break;
            case "search":
                searchOrders(request, response);
                break;
            case "delete":
                deleteOrder(request, response);
                break;
            default:
                listOrders(request, response);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");

        switch (action) {
            case "insert":
                insertOrder(request, response);
                break;
            case "update":
                updateOrder(request, response);
                break;
            default:
                listOrders(request, response);
                break;
        }
    }

    // 列出所有订单，按时间降序排列
    private void listOrders(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Order> orderList = orderDao.getAllOrders();
        request.setAttribute("orders", orderList);
        request.getRequestDispatcher("order_management.jsp").forward(request, response);
    }

    // 查询订单（按用户名或订单编号）
    private void searchOrders(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String query = request.getParameter("query").trim();
        List<Order> searchResults = new ArrayList<>();

        if (query != null && !query.isEmpty()) {
            try {
                // 如果输入的是数字，按订单编号查询
                int orderId = Integer.parseInt(query);
                Order order = orderDao.getOrderById(orderId);
                if (order != null) {
                    searchResults.add(order);
                }
            } catch (NumberFormatException e) {
                // 输入不是数字，按用户名查询
                searchResults = orderDao.getOrdersByUsername(query);
            }
        }
        request.setAttribute("orders", searchResults);
        request.getRequestDispatcher("order_management.jsp").forward(request, response);
    }

    // 插入新订单
    private void insertOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            int userId = Integer.parseInt(request.getParameter("userId"));
            double amount = Double.parseDouble(request.getParameter("amount"));
            String status = request.getParameter("status");

            User user = userDao.getUserById(userId);
            if (user == null) {
                response.sendRedirect("order_management.jsp?error=用户不存在");
                return;
            }

            Order newOrder = new Order(0, user, amount, status, new java.util.Date());
            orderDao.addOrder(newOrder);

            response.sendRedirect("OrderServlet?action=list");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("order_management.jsp?error=插入订单失败");
        }
    }

    // 更新订单
    private void updateOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            int orderId = Integer.parseInt(request.getParameter("orderId"));
            double amount = Double.parseDouble(request.getParameter("amount"));
            String status = request.getParameter("status");

            Order existingOrder = orderDao.getOrderById(orderId);
            if (existingOrder == null) {
                response.sendRedirect("order_management.jsp?error=订单不存在");
                return;
            }

            existingOrder.setAmount(amount);
            existingOrder.setStatus(status);
            orderDao.updateOrder(existingOrder);

            response.sendRedirect("OrderServlet?action=list");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("order_management.jsp?error=更新订单失败");
        }
    }

    // 删除订单
    private void deleteOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            int orderId = Integer.parseInt(request.getParameter("orderId"));
            orderDao.deleteOrder(orderId);
            response.sendRedirect("OrderServlet?action=list");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("order_management.jsp?error=删除订单失败");
        }
    }
}
